﻿using System;
using System.Collections.Generic;
using System.Reflection;
using BSpec.Conventions;

namespace BSpec.Specification
{
    public class SpecificationDataSet : SpecificationElement
    {
        private readonly Assembly _assembly;
        private readonly List<Concern> _concerns = new List<Concern>();

        protected SpecificationDataSet(Assembly assembly)
            : base(assembly.GetFriendlyName())
        {
            _assembly = assembly;
        }

        public Concern[] Concerns
        {
            get { return _concerns.ToArray(); }
        }

        public static SpecificationDataSet Build(Assembly assembly)
        {
            var specificationDataSet = new SpecificationDataSet(assembly);
            specificationDataSet.BuildConcerns();
            return specificationDataSet;
        }

        private void BuildConcerns()
        {
            foreach (var testFixtureType in _assembly.GetTestFixtureTypes())
            {
                AddConcernFor(testFixtureType);
            }
        }

        public void AddConcernFor(Type testFixtureType)
        {
            var concern = Concern.Create(testFixtureType);

            if (_concerns.HasElement(concern))
            {
                _concerns.GetElement(concern).AddScenarioFor(testFixtureType);
            }
            else
            {
                concern.AddScenarioFor(testFixtureType);
                _concerns.Add(concern);
            }
        }
    }
}